local string = string
local pairs  = pairs
local io     = io
local assert = assert
local table  = table
local print  = print 
module(...) -->name the package according to the filename

local function escape (s)
  if string.find(s, '[,"]') then
    s = '"' .. string.gsub(s, '"', '""') .. '"'
  end
  return s
end

function write (t)
  local s = ""
  local r,c
  for _,r in pairs(t) do
    for _,c in pairs(r) do
      --print(c) 
      s = string.format("%s%s,",s,escape(c)) 
    end
    s = s .. "\n"  
  end
  return s
end

function readcolumn (s)
  s = s .. ','        -- ending comma
  local t = {}        -- table to collect fields
  local fieldstart = 1
  repeat
    -- next field is quoted? (start with `"'?)
    if string.find(s, '^"', fieldstart) then
      local a, c
      local i  = fieldstart
      repeat
        -- find closing quote
        a, i, c = string.find(s, '"("?)', i+1)
      until c ~= '"'    -- quote not followed by quote?
      if not i then error('unmatched "') end
      local f = string.sub(s, fieldstart+1, i-1)
      table.insert(t, (string.gsub(f, '""', '"')))
      fieldstart = string.find(s, ',', i) + 1
    else                -- unquoted; find next comma
      local nexti = string.find(s, ',', fieldstart)
      local v = string.sub(s, fieldstart, nexti-1)
      if v ~= "" then
        table.insert(t, v)
      end
      fieldstart = nexti + 1
    end
  until fieldstart > string.len(s)
  return t
end

function read (s)
  s = s .. '\n'       -- ending comma
  local t = {}        -- table to collect fields
  local fieldstart = 1
  repeat
    local nexti = string.find(s, '\n', fieldstart)
    local t2 = readcolumn(string.sub(s, fieldstart, nexti-1))
    if #t2 ~= 0 then
      table.insert(t,t2)
    end
    fieldstart = nexti + 1
  until fieldstart > string.len(s)
  return t
end

function load(filename)
  local f = assert(io.open("C:\\projects\\classIV\\server\\simulator\\source\\"..filename..".csv", "r"))
  local d = f:read("*all")
  f:close()
  return read(d)  
end

function save(filename,t)
  local d = write(t)
  local f = assert(io.open("C:\\projects\\classIV\\server\\simulator\\source\\"..filename..".csv", "w"))
  f:write(d)
  f:close()
end
